﻿#include "measureworker.h"
#include "datacenter.h"
#include "ivdsmeasure.h"
#include <QThread>
#include <QTimer>
#include <QDebug>

class MeasureWorkerPrivate : public QObject
{
    Q_OBJECT
public:
    MeasureWorkerPrivate();
    ~MeasureWorkerPrivate();

    void start(const QString *arg = Q_NULLPTR);
    void stop();

signals:
    void measureError(bool stopTest);
    void measureResult(double voltage, double pulseWidth);

public slots:
    void onDataReady(const VdsMeasureDataPtr data);
    void onMeasureError(VdsError vdsError);

private:
    double average(const QList<double> &values);

private:
    QThread m_thread;
    QList<double> m_voltageList;
    QList<double> m_pulseWidthList;
};

MeasureWorker::MeasureWorker(IVdsMeasure *parent) : IComponent("MeasureWorker"), d(new MeasureWorkerPrivate)
{
    QObject::connect(DataCenter::instance(), &DataCenter::measureError, d, &MeasureWorkerPrivate::onMeasureError);
    QObject::connect(DataCenter::instance(), &DataCenter::dataReady, d, &MeasureWorkerPrivate::onDataReady);
    QObject::connect(d, &MeasureWorkerPrivate::measureError, parent, &IVdsMeasure::measureError);
    QObject::connect(d, &MeasureWorkerPrivate::measureResult, parent, &IVdsMeasure::measureResult);
}

MeasureWorker::~MeasureWorker()
{
    delete d;
}

void MeasureWorker::start(const QString *arg)
{
    d->start(arg);
}

void MeasureWorker::stop()
{
    d->stop();
}

void MeasureWorkerPrivate::start(const QString *arg)
{
    Q_UNUSED(arg)
    m_voltageList.clear();
    m_pulseWidthList.clear();
    m_thread.start();
}

void MeasureWorkerPrivate::stop()
{
    emit measureResult(average(m_voltageList), average(m_pulseWidthList));
    m_thread.quit();
    m_thread.wait();
}

MeasureWorkerPrivate::MeasureWorkerPrivate()
{
    moveToThread(&m_thread);
}

MeasureWorkerPrivate::~MeasureWorkerPrivate()
{
    stop();
}

void MeasureWorkerPrivate::onDataReady(const VdsMeasureDataPtr data)
{
    if (!data->overflow)
    {
        m_voltageList.append(data->vrms);
        m_pulseWidthList.append(data->pwid);
    }
}

void MeasureWorkerPrivate::onMeasureError(VdsError vdsError)
{
    if (vdsError == OpenSuccess)
    {
        emit measureError(false);
        return;
    }

    if (vdsError < ReadFail)
    {
        emit measureError(true);
    }
}

double MeasureWorkerPrivate::average(const QList<double> &values)
{
    double mean = 0.0;
    for (int i = 0; i < values.count(); i++)
    {
        mean += values[i] / values.count();
    }

    return mean;
}

#include "measureworker.moc"
